/*
 * @Description: 单位列表
 * @Author: Rfan
 * @Date: 2022-02-09 17:58:25
 * @LastEditTime: 2022-05-26 19:07:27
 */

import { useEffect, useState } from 'react';
import { Tree } from 'antd';
import classNames from 'classnames/bind';
import { observer } from 'mobx-react-lite';
import { fetchAllUnit } from '@/api/units';
import { arrToTree } from '@/utils';
import { appState } from '@/store/mobx';
import type { Key } from 'react';
import styles from './index.module.scss';

const cx = classNames.bind(styles);

interface IUnitNavProps {
  defaultValue: number;
  /** 阻止导航随全局单位变更 */
  changeWithGlobal?: boolean;
  onChange: any;
}

const UnitNav = (props: IUnitNavProps) => {
  const { defaultValue, changeWithGlobal = true, onChange } = props;
  // 单位列表
  const [unitList, setUnitList] = useState([]);
  // 选中的节点key，TODO：有子节点是需要测试
  const [selectKey, setSelectKey] = useState([]);

  // 加载时获取单位列表，获取成功后默认选中第一条并把第一条返回出去
  useEffect(() => {
    fetchAllUnit({}).then((res) => {
      console.log(res);
      const _unitList = res.data;
      const unitTree = arrToTree(_unitList);
      setUnitList(_unitList);
      if (defaultValue) {
        setSelectKey([defaultValue]);
        onChange(defaultValue, selectUnitById(defaultValue, _unitList));
      } else {
        setSelectKey([unitTree[0].id]);
        onChange(unitTree[0].id, unitTree[0]);
      }
    });
  }, []);

  useEffect(() => {
    if (unitList.length > 0 && changeWithGlobal && appState.unitId) {
      const unitId: number = (appState.unitId as number) || 0;
      setSelectKey([appState.unitId]);
      onChange(unitId, selectUnitById(unitId, unitList));
    }
  }, [appState.unitId]);

  const selectUnitById = (id: number, list?: any[]): any => {
    const _list = list || unitList;
    return _list.find((unit) => unit.id === id) || { id };
  };

  // Tree组件设置为受控组件，选中节点时设置选中的key并将选中的内容返回出去
  const onSelect = (selectedKeys: Key[], info: any) => {
    if (selectedKeys.length > 0) {
      setSelectKey(selectedKeys);
      onChange(selectedKeys[0], info.selectedNodes[0]);
    }
  };

  return (
    <div className={cx('container')}>
      <h6 className={cx('unit-header')}>单位列表</h6>
      <div className="unit-navs">
        {unitList.length > 0 && (
          <Tree
            onSelect={onSelect}
            treeData={arrToTree(unitList)}
            defaultExpandedKeys={unitList.map((unit) => unit.id)}
            fieldNames={{
              title: 'unitName',
              key: 'id'
            }}
            selectedKeys={selectKey}
          />
        )}
      </div>
    </div>
  );
};

export default observer(UnitNav);
